#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import os

print("创建简化版可视化图表...")

# 加载数据
df = pd.read_csv('学生社交媒体与人际关系数据集/学生社交媒体与人际关系数据集.csv')

# 创建输出目录
if not os.path.exists('static/charts'):
    os.makedirs('static/charts')

# 设置matplotlib支持中文
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

def create_chart(func, filename, title):
    try:
        func()
        plt.savefig(f'static/charts/{filename}', dpi=300, bbox_inches='tight')
        plt.close()
        print(f"✓ 成功创建: {filename}")
    except Exception as e:
        print(f"✗ 创建失败 {filename}: {e}")
        plt.close()

def chart1_usage_distribution():
    plt.figure(figsize=(10, 6))
    plt.hist(df['Avg_Daily_Usage_Hours'], bins=30, alpha=0.7, color='skyblue', edgecolor='black')
    plt.title('学生社交媒体每日使用时间分布', fontsize=16)
    plt.xlabel('每日使用时间 (小时)', fontsize=12)
    plt.ylabel('学生人数', fontsize=12)
    plt.axvline(df['Avg_Daily_Usage_Hours'].mean(), color='red', linestyle='--', 
               label=f'平均值: {df["Avg_Daily_Usage_Hours"].mean():.1f}小时')
    plt.legend()
    plt.grid(True, alpha=0.3)

def chart2_platform_distribution():
    plt.figure(figsize=(10, 8))
    platform_counts = df['Most_Used_Platform'].value_counts()
    plt.pie(platform_counts.values, labels=platform_counts.index, autopct='%1.1f%%', startangle=90)
    plt.title('社交媒体平台使用分布', fontsize=16)
    plt.axis('equal')

def chart3_mental_health():
    plt.figure(figsize=(12, 5))
    
    plt.subplot(1, 2, 1)
    plt.hist(df['Mental_Health_Score'], bins=10, alpha=0.7, color='lightgreen', edgecolor='black')
    plt.title('心理健康评分分布')
    plt.xlabel('心理健康评分')
    plt.ylabel('学生人数')
    
    plt.subplot(1, 2, 2)
    plt.scatter(df['Avg_Daily_Usage_Hours'], df['Mental_Health_Score'], alpha=0.5, color='orange')
    plt.title('使用时间与心理健康关系')
    plt.xlabel('每日使用时间 (小时)')
    plt.ylabel('心理健康评分')
    plt.grid(True, alpha=0.3)
    
    plt.tight_layout()

def chart4_academic_impact():
    plt.figure(figsize=(12, 5))
    
    plt.subplot(1, 2, 1)
    academic_impact = df['Affects_Academic_Performance'].value_counts()
    plt.bar(academic_impact.index, academic_impact.values, color=['lightcoral', 'lightgreen'])
    plt.title('社交媒体对学术表现的影响')
    plt.ylabel('学生人数')
    
    plt.subplot(1, 2, 2)
    affected = df[df['Affects_Academic_Performance'] == 'Yes']['Avg_Daily_Usage_Hours']
    not_affected = df[df['Affects_Academic_Performance'] == 'No']['Avg_Daily_Usage_Hours']
    plt.boxplot([affected, not_affected], labels=['影响', '不影响'])
    plt.title('使用时间与学术表现关系')
    plt.ylabel('每日使用时间 (小时)')
    
    plt.tight_layout()

def chart5_platform_addiction():
    plt.figure(figsize=(10, 8))
    platform_addiction = df.groupby('Most_Used_Platform')['Addicted_Score'].mean().sort_values()
    plt.barh(range(len(platform_addiction)), platform_addiction.values, color='orange', alpha=0.7)
    plt.yticks(range(len(platform_addiction)), platform_addiction.index)
    plt.title('各社交媒体平台平均成瘾评分', fontsize=14)
    plt.xlabel('平均成瘾评分')
    plt.grid(True, alpha=0.3, axis='x')

def chart6_demographics():
    plt.figure(figsize=(12, 8))
    
    plt.subplot(2, 2, 1)
    gender_counts = df['Gender'].value_counts()
    plt.pie(gender_counts.values, labels=gender_counts.index, autopct='%1.1f%%', colors=['lightblue', 'pink'])
    plt.title('性别分布')
    
    plt.subplot(2, 2, 2)
    academic_counts = df['Academic_Level'].value_counts()
    plt.pie(academic_counts.values, labels=academic_counts.index, autopct='%1.1f%%')
    plt.title('学历分布')
    
    plt.subplot(2, 2, 3)
    gender_usage = df.groupby('Gender')['Avg_Daily_Usage_Hours'].mean()
    plt.bar(gender_usage.index, gender_usage.values, color=['lightblue', 'pink'])
    plt.title('性别与平均使用时间')
    plt.ylabel('平均使用时间 (小时)')
    
    plt.subplot(2, 2, 4)
    academic_addiction = df.groupby('Academic_Level')['Addicted_Score'].mean()
    plt.bar(academic_addiction.index, academic_addiction.values, color=['lightgreen', 'lightyellow', 'lightcoral'])
    plt.title('学历与平均成瘾评分')
    plt.ylabel('平均成瘾评分')
    plt.xticks(rotation=45)
    
    plt.tight_layout()

# 创建所有图表
create_chart(chart1_usage_distribution, 'usage_distribution.png', '使用时间分布')
create_chart(chart2_platform_distribution, 'platform_distribution.png', '平台分布')
create_chart(chart3_mental_health, 'mental_health_analysis.png', '心理健康分析')
create_chart(chart4_academic_impact, 'academic_impact.png', '学术影响分析')
create_chart(chart5_platform_addiction, 'platform_addiction.png', '平台成瘾分析')
create_chart(chart6_demographics, 'demographics.png', '人口统计分析')

print("\n可视化图表创建完成！")
